import hashlib
import json
import time

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import *
from django.shortcuts import render
from django.contrib import messages

# Create your views here.chujinchujinchujin31232
from department.models import Department
from role.models import Role
from .models import User, SysLog

# def init(request:HttpRequest):
#     print("OK")
#     return render(request,"user/init.html")
#
#
# def getInit(request:HttpRequest):
#     users=User.objects.all()
#     print(users)
#     paginator = Paginator(users, 10)
#     cur_page = request.GET.get('page', 1)  # 得到默认的当前页
#     page = paginator.page(cur_page)
#     return render(request, 'user/init.html', locals())
from role.models import Menu


def init(request:HttpRequest):

    return render(request, 'user/init.html')


def getInit(request:HttpRequest):
        # 表格要展现的数据
    query=request.GET.get("keyword")
    if not query:
        print('a')
        users = User.objects.all()
    else:
        print('b')
        users=User.objects.filter(user_name__contains=query)
    # 处理成LayUi官方文档的格式
    lis = []
    for user in users:
        data = dict()
        data['id'] = user.id
        data['user_name'] = user.user_name
        data['role'] = user.role.name if user.role else None
        data['department'] = user.dept.title if user.dept else None
        data['telephone'] = user.telephone
        data['nickname'] = user.nickname
        data['email'] = user.email
        data['sex'] = user.sex
        data['last_login'] = user.last_login
        # 格式化时间的格式
        lis.append(data)
        # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    user_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    users = {"code": 0, "msg": "", "count": users.count(), "data": user_info}
    return JsonResponse(users)


def preAdd(request:HttpRequest):
    if request.method == "GET":
        roles=Role.objects.all()
        departments=Department.objects.all()
        return render(request, 'user/add_user.html', locals())
    elif request.method == "POST":
        username = request.POST['user_name']
        password_1 = request.POST['password']
        telephone = request.POST['telephone']
        role_id = request.POST['role_id']
        department_id = request.POST['department_id']
        nickname = request.POST['nickname']
        avatar = request.POST['avatar']
        email = request.POST['email']
        birthdate = request.POST['birthdate']
        sex = request.POST['sex']
        if not username or not password_1:
            return JsonResponse({'state':2})
        # password=hash_encrytion(password_1) 上线时再添加
        password=password_1
        if User.objects.filter(user_name=username):
            # messages.error(request,'用户名已存在')
            return JsonResponse({'state':0})
        users = User.objects.create(
            user_name=username,
            sex=sex,
            password=password,
            birthdate=birthdate,
            email=email,
            avatar=avatar,
            telephone=telephone,
            nickname=nickname,
            dept=Department.objects.get(id=department_id),
            role=Role.objects.get(id=role_id),
            add_user=User.objects.get(id=request.session['userid']),

        )
        return JsonResponse({'state':"1"})


def del_user(request:HttpRequest):
    uid=request.POST['id']
    user=User.objects.get(id=uid)
    user.delete()
    return JsonResponse({'state':"1"})


def hash_encrytion(password):
    hash = hashlib.sha256(b"#*)^#")
    hash.update(password.encode())
    return hash.hexdigest()


def login(request:HttpRequest):
    if request.method=="GET":
        if 'user' in request.session:
            return HttpResponseRedirect('/user/index')
        return render(request,"user/login.html")
    elif request.method=="POST":
        username=request.POST['username']
        password=request.POST['password']
        if not username or not password:
            return HttpResponse('用户名或密码不能为空')

        # password=hash_encrytion(password)上线时再添加
        users=User.objects.filter(password=password, user_name=username)
        if users:
            for user in users:
                request.session['user']=user
                request.session['user.department']=user.dept
                request.session['user.role']=user.role
                request.session['userid']=user.id
                user.last_login=time.strftime("%Y %b %d %H:%M:%S %a",time.localtime(time.time()))
                user.save()
            urls=[]
            for menu in Menu.objects.all():
                urls.append(menu.url)
            per_urls=[]
            nuser=request.session['user']
            if nuser.is_super==0:
                print(nuser)
                print(request.session['user.role'])
                for pmenu in nuser.role.permissions.all():
                    per_urls.append(pmenu.url)
                ban_urls=list(set(urls)-set(per_urls))
                print(ban_urls)
                request.session['per_urls']=per_urls
                request.session['ban_urls']=ban_urls
            return HttpResponseRedirect('login')
        messages.error(request, '用户名或密码不正确')
        return HttpResponseRedirect('/user/login')
def index(request:HttpRequest):
    userid=request.session['user'].id
    user=User.objects.get(id=userid)
    user_name=user.user_name
    if user.is_super==1:
        menus=Menu.objects.all()
    else:
        menus=request.session['user.role'].permissions.all()
    parent_menus = []
    child_menus=[]
    for menu in menus:
        if not menu.parent:
            parent_menus.append(menu)
        else:
            child_menus.append(menu)
    print(parent_menus,child_menus)
    return render(request,"index.html",locals())


def logout(request:HttpRequest):
    request.session.delete()
    return HttpResponseRedirect('/')


def edit(request:HttpRequest):
    if request.method == "GET":
        roles = Role.objects.all()
        departments = Department.objects.all()
        uid=request.GET.get('id')
        try:
            user=User.objects.get(id=uid)
        except:
            return HttpResponseNotFound
        return render(request, 'user/edit_user.html', locals())
    elif request.method == "POST":
        uid=request.POST['id']
        username = request.POST['user_name']
        password_1 = request.POST['password']
        telephone = request.POST['telephone']
        role_id = request.POST['role_id']
        department_id = request.POST['department_id']
        nickname = request.POST['nickname']
        email = request.POST['email']
        birthdate = request.POST['birthdate']
        sex = request.POST['sex']
        if not username or not password_1:
            # messages.error('用户名或密码为空')
            return JsonResponse({'state': 2})
        # password=hash_encrytion(password_1) 上线时再添加
        password = password_1
        if User.objects.filter(Q(user_name=username)&~Q(id=uid)):
            return JsonResponse({'state': 0})
        try:
            user = User.objects.get(id=uid)
        except:
            return JsonResponse({'state': 3})
        user.user_name=username
        user.password=password_1
        user.sex=sex
        user.nickname=nickname
        user.birthdate=birthdate
        user.telephone=telephone
        user.email = email
        try:
            user.role=Role.objects.get(id=role_id)
            user.dept=Department.objects.get(id=department_id)
        except:
            user.role=None
            user.dept=None

        user.save()
        return JsonResponse({'state': "1"})


def detail(request:HttpRequest):
    if request.method == "GET":
        uid = request.GET.get('id')
        roles = Role.objects.all()
        departments = Department.objects.all()
        try:
            user = User.objects.get(id=uid)
        except:
            return HttpResponseNotFound
        return render(request, 'user/detail_user.html', locals())


def check(request:HttpRequest):
    json_str=request.body
    py_obj=json.loads(json_str)
    user_name=py_obj['name']
    if User.objects.filter(user_name=user_name):
        info='用户名已存在'
    else:
        info='用户名可用'
    return JsonResponse({"code":200 ,"info":info})


def personal(request:HttpRequest):
    if request.method == "GET":
        uid = request.GET.get('id')
        try:
            user = request.session['user']
        except:
            return HttpResponseNotFound
        return render(request, 'user/personal.html', locals())
    elif request.method == "POST":
        uid = request.POST['id']
        password_1 = request.POST['password']
        telephone = request.POST['telephone']
        nickname = request.POST['nickname']
        email = request.POST['email']
        birthdate = request.POST['birthdate']
        sex = request.POST['sex']
        try:
            user = User.objects.get(id=uid)
        except:
            return JsonResponse({'state': 3})
        user.password = password_1
        user.sex = sex
        user.nickname = nickname
        user.birthdate = birthdate
        user.telephone = telephone
        user.email=email

        user.save()
        request.session['user']=user
        return JsonResponse({'state': "1"})


def log(request:HttpRequest):
    return render(request,"user/log.html",locals())


def log_init(request):
    # 表格要展现的数据
    query = request.GET.get("keyword")
    if not query:
        print('a')
        logs = SysLog.objects.order_by("-add_time")
    else:
        print('b')
        logs = SysLog.objects.filter(id=query)
    # 处理成LayUi官方文档的格式
    lis = []
    for log in logs:
        data = dict()
        data['id'] = log.id
        data['content'] = log.content
        data['user_name'] = log.operate_user.user_name
        data['add_time'] = log.add_time
        lis.append(data)
        # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    log_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    logs = {"code": 0, "msg": "", "count": logs.count(), "data": log_info}
    return JsonResponse(logs)